package com.nopay.cdxphone.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewbinding.ViewBinding;

import com.azhon.basic.eventbus.MessageEvent;
import com.azhon.basic.utils.ActivityManagerUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.nopay.cdxphone.utils.GsonUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import com.nopay.cdxphone.net.AssetsRetrofit;
import com.nopay.cdxphone.net.HttpApi;
import com.nopay.cdxphone.ui.ativity.LoginActivity;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Retrofit;


/**
 * @ProjectName: guizhou_assets
 * @Package: dhc.guizhou.assets.base
 * @ClassName: BaseFragment
 * @Description: java类作用描述
 * @Author: Kawaii's cat
 * @CreateDate: 2020-5-18 13:57
 * @UpdateUser: 更新者：
 * @UpdateDate: 2020-5-18 13:57
 * @UpdateRemark: 更新说明：
 * @Version: 1.0
 */
public abstract class BaseFragment<T extends ViewBinding> extends Fragment {

    private static final String TAG = BaseFragment.class.getSimpleName();
    protected boolean bIsViewCreated;
    protected boolean bIsDataLoaded;
    private View rootView;
    protected T binding;
    protected Activity mActivity;
    private Retrofit retrofit = AssetsRetrofit.getInstance().getRetrofit();
    protected HttpApi api = retrofit.create(HttpApi.class);

    @Nullable
    @Override
    @SuppressLint("ResourceType")
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        bIsViewCreated = true;
        binding = getBinding(container);
        if(binding == null) return null;

        if (getUserVisibleHint() && !bIsDataLoaded) {
            loadData();
            bIsDataLoaded = true;
        }
        return binding.getRoot();
    }

    private T getBinding(@Nullable ViewGroup container) {
        try {
            Type superclass = getClass().getGenericSuperclass();
            //获得父类的泛型参数的实际类型
            Class<?> aClass = (Class<?>) ((ParameterizedType) superclass).getActualTypeArguments()[0];
            //获取inflate方法 传入相应的参数
            Method method = aClass.getDeclaredMethod("inflate", LayoutInflater.class, ViewGroup.class, boolean.class);
            //执行inflate方法
            binding = (T) method.invoke(null, getLayoutInflater(), container, false);
            return binding;
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        bIsViewCreated = false;
        bIsDataLoaded = false;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (isVisibleToUser && bIsViewCreated && !bIsDataLoaded) {
            loadData();
            bIsDataLoaded = true;
        }
    }

    /**
     * 加载数据
     */
    protected abstract void loadData();

    /**
     * 退出当前账号
     */
    protected void exitCurrentAccount() {

        ActivityManagerUtils.getInstance().exitAllActivity();
        SharedPreferences share = getActivity().getSharedPreferences("Login",
                Context.MODE_PRIVATE);
        share.edit().putBoolean("LoginBool", false).commit();
        SPUtils.getInstance().clear();
        startActivity(new Intent(getContext(), LoginActivity.class));
        ToastUtils.showShort("账号登录已失效...请重新登录");
        return;
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mActivity = getActivity();
    }

    public RelativeLayout.LayoutParams setStatusBar(Activity activity) {
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                getStatusBarHeight(activity));
        return lp;
    }

    /**
     * 获取状态栏的高度
     *
     * @param context 当前上下文
     * @return 高度值
     */
    public int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen",
                "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDataEvent(MessageEvent msg) {
        switch (msg.msgType) {
        }
    }

    protected RequestBody getRequestBody(Object object) {
        String jsonStr = GsonUtils.toJson(object);
        return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonStr);
    }
}
